package com.cicadamob.contact.api.service;

import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;

public class DBManager {
	 private AtomicInteger dbOpenCount = new AtomicInteger();//计数器
	 private static DBManager instance;
	 private static AppDbHelper sqlLiteTool;
	 private SQLiteDatabase database;
	 
	 public static synchronized DBManager getInstance(Context mContext) {
	  if (instance == null) {
	   synchronized (DBManager.class) {
	    if (instance == null) {
	     instance = new DBManager(mContext);
	    }
	   }
	  }
	  return instance;
	 }
	 
	 private DBManager(Context mContext) {
	  sqlLiteTool =  AppDbHelper.newInstance(mContext);
	 }
	 
	 @SuppressLint("NewApi")
	public synchronized SQLiteDatabase openDatabase() {
	  if (dbOpenCount.incrementAndGet() == 1) {
	   database = sqlLiteTool.getWritableDatabase();
	   if (Build.VERSION.SDK_INT >= 11) {
	    database.enableWriteAheadLogging();// 允许读写同时进行
	   }
	  }
	  return database;
	 }
	 public synchronized void closeDatabase() {
	  if (dbOpenCount.decrementAndGet() == 0) {
	   database.close();
	   database = null;
	  }
	 }
	}
